/**
 * 获取当前时间的时间戳（毫秒）
 * @returns 当前时间的毫秒级时间戳，等同于 Date.now()
 */
export function getNowMillisecond(): number {
  return Date.now();
}

/**
 * 将毫秒数格式化为 HH:mm:ss
 */
export function formatMilliseconds(ms: number): string {
  const totalSeconds = Math.floor(ms / 1000);
  const hours = Math.floor(totalSeconds / 3600);
  const minutes = Math.floor((totalSeconds % 3600) / 60);
  const seconds = totalSeconds % 60;
  return `${String(hours).padStart(2, "0")}:${String(minutes).padStart(
    2,
    "0"
  )}:${String(seconds).padStart(2, "0")}`;
}

/**
 * 判断时间戳是否是今天（默认使用本地时间，可传入服务器时间）
 */
export function isToday(target: number, now: number = Date.now()): boolean {
  const t = new Date(target);
  const n = new Date(now);
  return isSameDate(t, n);
}

/**
 * 判断是否昨天
 */
export function isYesterday(target: number, now: number = Date.now()): boolean {
  const yesterday = new Date(now - 24 * 60 * 60 * 1000);
  return isSameDate(new Date(target), yesterday);
}

/**
 * 判断是否前天
 */
export function isBeforeYesterday(
  target: number,
  now: number = Date.now()
): boolean {
  const beforeYesterday = new Date(now - 48 * 60 * 60 * 1000);
  return isSameDate(new Date(target), beforeYesterday);
}

/**
 * 判断是否上个月
 */
export function isLastMonth(target: number, now: number = Date.now()): boolean {
  const t = new Date(target);
  const n = new Date(now);
  return (
    t.getFullYear() === n.getFullYear() && t.getMonth() === n.getMonth() - 1
  );
}

/**
 * 格式化时间戳为 年月日
 */
export function formatTimeToYMD(timestamp: number | string): string {
  const date = new Date(timestamp);
  if (isNaN(date.getTime())) return "无效时间";
  return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;
}

// 私有辅助函数
function isSameDate(d1: Date, d2: Date): boolean {
  return (
    d1.getFullYear() === d2.getFullYear() &&
    d1.getMonth() === d2.getMonth() &&
    d1.getDate() === d2.getDate()
  );
}
